<?php
require_once "../includes/common.php";
require_once BASE_PATH.'/class/User.class.php';
require_once "../islogin.php";

class UserApi {
    private $user;

    public function __construct() {
        $this->user = new User(); // 实例化 User 类
    }

    public function handleRequest() {
        if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
            $this->respond(json_encode(['message' => '只接受 POST 请求']));
            return;
        }

        if (!isset($_GET['type'])) {
            $this->respond(json_encode(['message' => '无效的 type 参数']));
            return;
        }



        switch ($_GET['type']) {
            case 'reg':
                $this->register();
                break;
            case 'souser':
                $this->souser();
                break;

            default:
                $this->respond(json_encode(['error' => '无效的 type 参数']));
                break;
        }
    }

    private function register() {
        $phone = $_POST['phone'] ?? '';
        $password = $_POST['password'] ?? '';
        $pwd_confirm = $_POST['password_confirm'] ?? '';

        $result = $this->user->register($phone, $password, $pwd_confirm);
        $this->respond($result);
    }
    private function souser() {
        $uid = $_POST['uid'] ?? '';
        $key = $_POST['keywords'] ?? '';
        $page = isset($_POST['page']) ? intval($_POST['page']) : 1;
        $limit = 12;

        global $user_info; // 使用 global 关键字引用外部变量
        if($uid){
            if ($uid!=$user_info['message']['user_id']) {
                $this->respond(json_encode(['message' => 'uid error!']));
                return;
            }
        }

        $result = $this->user->searchUser($uid, $key, $page, $limit);
        $this->respond($result);
    }

    private function respond($data) {
        header('Content-Type: application/json');
        echo $data;
        exit;
    }
}

$api = new UserApi();
$api->handleRequest();


